﻿(function (ns) {
    ZYCLib.RegNameSpace(ns).Sign = (function () {
        var procceing = false;

        var ShowErrorMessage = function (message) {
            $("#divLoginTip").removeClass("none");
            $("#spErrorMsg").html("<i></i>" + message);
        };

        var HideErrorMessage = function () {
            $("#divLoginTip").addClass("none");
        };

        var CheckInput = function (id, message) {
            var isPass = true;
            if (id.length > 0) {
                if ($("#" + id).val() === "") {
                    ShowErrorMessage(message);
                    $("#" + id).focus();
                    isPass = false;
                }
            }
            return isPass;
        };

        var SetLogNameCookies = function (userNameValue) {
            var checked = document.getElementById("chkRememberAccount").checked;
            if (!checked) {
                ZYCLib.Utils.LocalStorage.SetCookie("lnXedStgli", "", 86400);
            } else {
                ZYCLib.Utils.LocalStorage.SetCookie("lnXedStgli", userNameValue, 86400);
            }
        };

        var backPreviousUrl = function (returnURL)
        {
            if (returnURL !== "" && returnURL.toLowerCase().indexOf("/sign/") < 0 && returnURL.toLowerCase().indexOf("register.html") < 0) {
                var re = new RegExp(["((http|https)://[a-zA-Z0-9\._-]+\.(zyccst|zyctd)\.(net|com)", ")"].join(""));
                if (re.test(returnURL)) {
                    window.location.href = returnURL;
                } else {
                    window.location.href = 'http://www' + ZYCLib.Domain;
                }
            } else {
                window.location.href = 'http://www' + ZYCLib.Domain;
            }
        }

        //function Trim(str) {
        //    return str.replace(/(^\s*)|(\s*$)/g, "");
        //}

        //function _setUserKeywordRecordCookie(returnURL, name) {
        //    var keywords = ZYCLib.Utils.LocalStorage.GetCookie("KeyWord__");
        //    var arr = "";
        //    if (keywords != null)
        //        arr = keywords.split("|");
        //    if (arr.length < 11 && ZYCLib.CurrentUser.PerID > 0) {
        //        var params =
        //        {
        //            CommandName: "SearchDataService/QueryUserSearchKeyword",
        //            Data: {
        //                PerID: ZYCLib.CurrentUser.PerID,
        //                TopN: (11 - arr.length)
        //            }
        //        };

        //        ZYCLib.Web.JsonAjax.PostData(params.CommandName, params.Data,
        //            function (transport) {
        //                var jsondata = transport.responseJSON;
        //                if (jsondata == null || jsondata.Data == undefined || jsondata.Data.SearchListData == null) {
        //                    $(".err").parent().show();
        //                    return;
        //                }
        //                var arr = jsondata.Data.SearchListData;
        //                for (var i = 0; i < arr.length; i++) {
        //                    if (arr[i] !== null)
        //                        ZYCLib.Utils.LocalStorage.AppendTo("KeyWord__", Trim(arr[i].Keyword), false);
        //                }
        //            },
        //            function() {
        //                SetLogNameCookies(name);
        //                if (returnURL !== "" && returnURL.toLowerCase().indexOf("/sign/") < 0 && returnURL.toLowerCase().indexOf("register.html") < 0) {
        //                    var re = new RegExp("(http|https)://[a-zA-Z0-9\._-]+" + ZYCLib.Domain);
        //                    if (re.test(returnURL)) {
        //                        window.location.href = returnURL;
        //                    } else {
        //                        window.location.href = 'http://www' + ZYCLib.Domain;
        //                    }
        //                } else {
        //                    window.location.href = 'http://www' + ZYCLib.Domain;
        //                }
        //            }
        //        );
        //    } else {
        //        if (returnURL !== '' && returnURL.toLowerCase().indexOf("/sign/") < 0 && returnURL.toLowerCase().indexOf("register.html") < 0) {
        //            var re = new RegExp("(http|https)://[a-zA-Z0-9\._-]+" + ZYCLib.Domain);
        //            if (re.test(returnURL)) {
        //                window.location.href = returnURL;
        //            } else {
        //                window.location.href = 'http://www' + ZYCLib.Domain;
        //            }
        //        } else {
        //            window.location.href = 'http://www' + ZYCLib.Domain;
        //        }
        //    }
        //}

        var RryLoginCount = "lgc";
        var isNeedCheckCode = false;
        var Login = function (returnURL) {
            HideErrorMessage();
            if (!CheckInput("txtLoginName", "请输入用户名")) return;
            if (!CheckInput("txtPassword", "请输入密码")) return;
            var _LoginCount = ZYCLib.Utils.LocalStorage.Get(RryLoginCount);
            if (typeof(_LoginCount) !== "undefined" && _LoginCount != null) {
                ZYCLib.Utils.LocalStorage.Set(RryLoginCount, parseInt(_LoginCount) + 1);
            }
            else {
                ZYCLib.Utils.LocalStorage.Set(RryLoginCount, 1);
            }
            if (_LoginCount >= 5) {
                isNeedCheckCode = true;
                $("#validcodeContainer").removeClass("none");
                if (!CheckInput("textCheckCode", "请输入验证码")) return;
            }

            var usernameIpt = $("#txtLoginName");
            var userpwdIpt = $("#txtPassword");

            $("#btnLogin").html("正在登录…");
            if (procceing === true) {
                ShowErrorMessage("正在处理中，请稍后。");
                return;
            }
            procceing = true;

            var params =
                {
                    CommandName: "UserSignService/SignIn",
                    Data: { LoginName: usernameIpt.val(), Password: userpwdIpt.val(), IsNeedCheckCode: isNeedCheckCode, CheckCode : $("#textCheckCode").val() }
                };
            ZYCLib.Web.JsonAjax.NPostData(params.CommandName, params.Data,
                function (jsondata) {
                    if (jsondata != null) {
                        var sso;
                        if (jsondata.ErrorCode === 0) {
                            ZYCLib.Utils.LocalStorage.Remove(RryLoginCount);
                            ZYCLib.CurrentUser.PerID = jsondata.Data.PerID;
                            sso = jsondata.Data.SsoList;
                            if (sso && sso.length > 0) {
                                ZYCLib.CrossDomain.SingleSignOn.LoginSso(sso, function () {
                                    backPreviousUrl(returnURL);
                                });
                            } else backPreviousUrl(returnURL);
                        }
                        else {
                            $("#btnLogin").html("登录");//innerText firefox是不支持的
                            if (jsondata.ErrorCode === 103) {
                                isNeedCheckCode = true;
                                $("#validcodeImg").click();
                                ShowErrorMessage(jsondata.ErrorMessage);
                            }
                            else if (jsondata.ErrorCode === 106 || jsondata.ErrorCode === 107) {
                                SetLogNameCookies(usernameIpt.value);
                                sso = jsondata.Data.SsoList;
                                if (sso && sso.length > 0) {
                                    ZYCLib.CrossDomain.SingleSignOn.LoginSso(sso, function () {
                                        window.location.href = ["http://www", ZYCLib.Domain, "/webpage/forceactivation"].join("");
                                    });
                                } else window.location.href = ["http://www", ZYCLib.Domain, "/webpage/forceactivation"].join("");
                            }
                            else if (jsondata.ErrorCode === 9 || jsondata.ErrorCode === 101) {
                                ShowErrorMessage("登录账号或密码错误。");
                            } else {
                                ZYCLib.UI.MessageBox.Alert(jsondata.ErrorMessage, 3, function () {
                                    $("#validcodeImg").click();
                                });
                            }
                        }
                        //else if (jsondata.ErrorCode === 107) {
                        //    SetLogNameCookies(usernameIpt.value);
                        //    window.location.href = "/Sign/RegSuccess.aspx?notact=1";
                        //}
                    }
                    $("#validcodeImg").click();
                    procceing = false;
                },
                function () {
                    SetLogNameCookies(usernameIpt.val());
                },
                {
                    Error106: function (jsondata) {
                        ZYCLib.UI.MessageBox.Alert(unescape(jsondata.ErrorMessage), 3, function () {
                            var inputItems = [];
                            var inputItem = { Id: "txtPerID", Name: "PerID", Type: "hidden", Value: jsondata.Data.PerID };
                            inputItems.push(inputItem);
                            ZYCLib.Utils.Builder.BuildFormAndSubmit("post", "http://www" + ZYCLib.Domain + "/WebPage/ForceActivation", "_self", inputItems);
                        });
                    }
                }
            );
        };

        var LoginInit = function (returnURL) {
            var bindLoginEventItems = ["txtLoginName", "txtPassword", "textCheckCode"];
            $.each(bindLoginEventItems, function(index, val) {
                $("#" + val).on("keypress", function(event) {
                    var ev = event || window.event;
                    if (ev.keyCode === 13) {
                        Login(returnURL);
                        return false;
                    }
                    return true;
                });
            });

            $("#btnLogin").on("click", function() {
                Login(returnURL);
            });

            $("#txtLoginName").focus();
            var _loginName = ZYCLib.Utils.LocalStorage.GetCookie("lnXedStgli");
            if (_loginName != null) {
                $("#txtLoginName").val(_loginName);
                document.getElementById("chkRememberAccount").checked = true;
            }
        };

        return {
            LoginInit: LoginInit
        };
    })();
})("Page");